#include <fcntl.h>
#include <sys/sendfile.h>
#include <iostream>

#include <sys/types.h> 
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>

#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <fcntl.h>
#include <sys/stat.h>

#include <sys/sendfile.h>
#include <iostream>

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main()
{
	int fd = open("/etc/cron.d/anacron", O_RDONLY);
	if (fd < 0)
		return -1;
	struct stat stat_buff;
	fstat(fd,&stat_buff);

        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
                std::cerr << "Error opening socket" << std::endl;
                return 1;
        }

        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
        int portno = 7171;
        serv_addr.sin_port = htons(portno);

        if(connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "ERROR connecting" << std::endl;
                return 1;
        }
	std::cout << "connected to server\n";

	char b2[1];
	write(sockfd,"file", 5);
	read(sockfd,b2,1);
	write(sockfd, &stat_buff.st_size, sizeof(off_t));

	std::cout << stat_buff.st_size << std::endl;

	off_t *p = NULL;
	const int SIZE = 1024;
	char b[7];
	if(read(sockfd,b,7) == 7)
	{
		sendfile(sockfd,fd,p,SIZE);
		while(sendfile(sockfd,fd,p,SIZE))
			;;
	}
	std::cout << "   :sending finished\n";
	close(sockfd);
	close(fd);
	return 0;
}
